package entry75;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class LightStringList implements Serializable {
	private static final long serialVersionUID = -4069333492618847544L;

	private transient int size = 0;
	private transient Entry head = null;

	public static class Entry implements Serializable {
		private static final long serialVersionUID = -2049500325918137196L;

		public Entry(String data) {
			this.data = data;
		}

		String data;
		Entry previous, next;
	}

	public void add(String s) {
		Entry e = new Entry(s);

		if (head == null) {
			head = e;
		} else {
			Entry t = head;
			while (t.next != null) {
				t = t.next;
			}
			t.next = e;
			e.previous = t;
		}
		size++;
	}

	public String get(int index) {
		return getEntry(index).data;
	}

	private Entry getEntry(int index) {
		sizeException(index);

		Entry e = head;
		for (int i = 0; i < index; i++) {
			e = e.next;
		}
		return e;
	}

	private void sizeException(int index) {
		if (index >= size) {
			throw new RuntimeException(index + "(은)는 범위를 벗어납니다.");
		}
	}

	public int size() {
		return size;
	}

	public void remove(int i) {
		Entry e = getEntry(i);

		if (e.previous == null) {
			head = e.next;
		} else {
			e.previous.next = e.next;
		}

		if (e.next != null) {
			e.next.previous = e.previous;
		}

		size--;
	}
	
private void writeObject(ObjectOutputStream s) throws IOException {
	s.defaultWriteObject();
	s.writeInt(size);
	
	for(Entry e=head;e != null;e = e.next) {
		s.writeObject(e.data);
	}
}

private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
	s.defaultReadObject();
	int number = s.readInt();
	
	for(int i=0;i<number;i++) {
		add((String)s.readObject());
	}
}
}